<template>
  <div class="profile-page">
    <div class="container">
      <div class="profile-content">
        <!-- 个人信息卡片 -->
        <div class="profile-card">
          <div class="profile-header">
            <div class="avatar-section">
              <el-avatar :size="120" :src="userInfo.avatar">
                <el-icon><User /></el-icon>
              </el-avatar>
              <el-upload
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :http-request="handleAvatarUpload"
                :disabled="uploadingAvatar"
                accept="image/*"
              >
                <el-button class="change-avatar-btn" :loading="uploadingAvatar">
                  <el-icon v-if="!uploadingAvatar"><Camera /></el-icon>
                  {{ uploadingAvatar ? '上传中...' : '更换头像' }}
                </el-button>
              </el-upload>
            </div>
            <div class="user-info">
              <h2>{{ userInfo.name }}</h2>
              <p class="user-email">{{ userInfo.email }}</p>
              <p class="user-phone" v-if="userInfo.phone">{{ userInfo.phone }}</p>
              <p class="user-detail" v-if="userInfo.realName">真实姓名：{{ userInfo.realName }}</p>
              <p class="user-detail" v-if="userInfo.gender">
                性别：{{ userInfo.gender === 1 ? '男' : userInfo.gender === 2 ? '女' : '未知' }}
              </p>
              <p class="user-detail" v-if="userInfo.birthday">生日：{{ userInfo.birthday }}</p>
              <div class="user-stats">
                <div class="stat-item">
                  <span class="stat-number">{{ userInfo.totalOrders }}</span>
                  <span class="stat-label">总订单</span>
                </div>
                <div class="stat-item">
                  <span class="stat-number">{{ userInfo.totalReviews }}</span>
                  <span class="stat-label">评价数</span>
                </div>
                <div class="stat-item">
                  <span class="stat-number">{{ userInfo.totalFavorites }}</span>
                  <span class="stat-label">收藏数</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 功能菜单 -->
        <div class="profile-menu">
          <div class="menu-grid">
            <div class="menu-item" @click="$router.push('/orders')">
              <el-icon><Document /></el-icon>
              <span>我的订单</span>
            </div>
            <div class="menu-item" @click="$router.push('/favorites')">
              <el-icon><Star /></el-icon>
              <span>我的收藏</span>
            </div>
            <div class="menu-item" @click="$router.push('/reviews')">
              <el-icon><ChatDotRound /></el-icon>
              <span>我的评价</span>
            </div>
            <div class="menu-item" @click="showEditProfile">
              <el-icon><Edit /></el-icon>
              <span>编辑资料</span>
            </div>
            <div class="menu-item" @click="logout">
              <el-icon><SwitchButton /></el-icon>
              <span>退出登录</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 编辑资料对话框 -->
    <el-dialog v-model="editProfileVisible" title="编辑资料" width="600px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="真实姓名">
          <el-input v-model="editForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="editForm.idCard" placeholder="请输入身份证号" maxlength="18" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="editForm.gender">
            <el-radio :label="0">未知</el-radio>
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生日">
          <el-date-picker
            v-model="editForm.birthday"
            type="date"
            placeholder="选择生日"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        
        <!-- 密码修改区域 -->
        <el-divider content-position="left">修改密码（选填）</el-divider>
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="editForm.password"
            type="password"
            placeholder="留空则不修改密码"
            show-password
            autocomplete="new-password"
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="editForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
            autocomplete="new-password"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editProfileVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getUserInfo, updateUserInfo, uploadImage } from '../../api/user'
import { useUserStore } from '../../stores/user'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()

// 对话框显示状态
const editProfileVisible = ref(false)
const uploadingAvatar = ref(false)

// 表单引用
const editFormRef = ref()

// 用户信息
const userInfo = ref({
  name: '',
  email: '',
  phone: '',
  realName: '',
  idCard: '',
  avatar: '',
  gender: 0,
  birthday: '',
  totalOrders: 0,
  totalReviews: 0,
  totalFavorites: 0
})

// 编辑表单
const editForm = reactive({
  name: '',
  email: '',
  phone: '',
  realName: '',
  idCard: '',
  gender: 0,
  birthday: '',
  password: '',
  confirmPassword: ''
})

// 自定义验证：确认密码
const validateConfirmPassword = (rule, value, callback) => {
  if (editForm.password && !value) {
    callback(new Error('请再次输入新密码'))
  } else if (value && value !== editForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 编辑表单验证规则
const editRules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  idCard: [
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  password: [
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 初始化
onMounted(async () => {
  await loadUserInfo()
  // 初始化编辑表单
  Object.assign(editForm, {
    name: userInfo.value.name,
    email: userInfo.value.email,
    phone: userInfo.value.phone,
    realName: userInfo.value.realName,
    idCard: userInfo.value.idCard,
    gender: userInfo.value.gender,
    birthday: userInfo.value.birthday
  })
})

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const data = await getUserInfo()
    userInfo.value = {
      name: data.username || '用户',
      email: data.email || '',
      phone: data.phone || '',
      realName: data.realName || '',
      idCard: data.idCard || '',
      avatar: data.avatar || 'https://api.dicebear.com/7.x/avataaars/svg?seed=' + (data.username || 'User'),
      gender: data.gender || 0,
      birthday: data.birthday || '',
      totalOrders: data.totalOrders || 0,
      totalReviews: data.totalReviews || 0,
      totalFavorites: data.totalFavorites || 0
    }
    // 同步更新编辑表单数据
    Object.assign(editForm, {
      name: userInfo.value.name,
      email: userInfo.value.email,
      phone: userInfo.value.phone,
      realName: userInfo.value.realName,
      idCard: userInfo.value.idCard,
      gender: userInfo.value.gender,
      birthday: userInfo.value.birthday
    })
  } catch (error) {
    console.error('加载用户信息失败:', error)
    ElMessage.error('加载用户信息失败')
  }
}

// 更换头像
const beforeAvatarUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB！')
    return false
  }
  return true
}

const handleAvatarUpload = async (options) => {
  const { file } = options
  uploadingAvatar.value = true
  
  try {
    // 上传图片
    const result = await uploadImage(file)
    
    if (result.success) {
      // 更新用户头像
      await updateUserInfo({ avatar: result.url })
      
      // 更新本地显示
      userInfo.value.avatar = result.url
      
      // 更新 store 中的用户信息
      await userStore.fetchUserInfo()
      
      ElMessage.success('头像更新成功！')
    } else {
      ElMessage.error(result.message || '上传失败')
    }
  } catch (error) {
    console.error('上传头像失败:', error)
    ElMessage.error('上传失败，请稍后重试')
  } finally {
    uploadingAvatar.value = false
  }
}

// 显示编辑资料
const showEditProfile = () => {
  // 重置密码字段
  editForm.password = ''
  editForm.confirmPassword = ''
  editProfileVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  const valid = await editFormRef.value.validate()
  if (!valid) return
  
  try {
    // 构建更新数据对象
    const updateData = {
      username: editForm.name,
      email: editForm.email,
      phone: editForm.phone,
      realName: editForm.realName,
      idCard: editForm.idCard,
      gender: editForm.gender,
      birthday: editForm.birthday
    }
    
    // 如果填写了新密码，则包含密码字段
    if (editForm.password) {
      updateData.password = editForm.password
    }
    
    // 调用API更新用户信息
    await updateUserInfo(updateData)
    editProfileVisible.value = false
    
    // 如果修改了密码，提示用户重新登录
    if (editForm.password) {
      ElMessageBox.alert('密码已修改，请重新登录', '提示', {
        confirmButtonText: '确定',
        callback: () => {
          userStore.logoutAction()
          router.push('/login')
        }
      })
    } else {
      ElMessage.success('资料更新成功')
      // 重新加载用户信息
      await loadUserInfo()
    }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    ElMessage.error(error.message || '更新失败，请稍后重试')
  }
}

// 退出登录
const logout = () => {
  ElMessageBox.confirm('确定要退出登录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 调用 store 的登出方法
    userStore.logoutAction()
    ElMessage.success('已退出登录')
    router.push('/login')
  })
}

</script>

<style scoped>
.profile-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 20px 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.profile-content {
  space-y: 30px;
}

.profile-card {
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.profile-header {
  display: flex;
  gap: 40px;
  align-items: center;
}

.avatar-section {
  text-align: center;
}

.change-avatar-btn {
  margin-top: 15px;
}

.user-info h2 {
  font-size: 2rem;
  color: #333;
  margin-bottom: 10px;
}

.user-email,
.user-phone,
.user-detail {
  color: #666;
  margin-bottom: 5px;
  font-size: 1.1rem;
}

.user-stats {
  display: flex;
  gap: 40px;
  margin-top: 30px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 2rem;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  color: #666;
  font-size: 0.9rem;
}

.profile-menu {
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.menu-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.menu-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  padding: 30px 20px;
  border: 1px solid #eee;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.menu-item:hover {
  border-color: #409eff;
  background: #f0f9ff;
}

.menu-item .el-icon {
  font-size: 2rem;
  color: #409eff;
}

.menu-item span {
  font-size: 1.1rem;
  color: #333;
  font-weight: 500;
}

@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    text-align: center;
  }
  
  .user-stats {
    justify-content: center;
  }
  
  .menu-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>


